<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="实例名" prop="instance">
        <el-select v-model="queryParams.instance" placeholder="请选择实例名" clearable filterable allow-create
          style="width: 200px" @keyup.enter="handleQuery">
          <el-option v-for="item in instanceOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务器" prop="server">
        <el-select v-model="queryParams.server" placeholder="请选择服务器" clearable filterable allow-create
          style="width: 200px" @keyup.enter="handleQuery">
          <el-option v-for="item in serverOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="组名" prop="group">
        <el-select v-model="queryParams.group" placeholder="请选择组名" clearable filterable allow-create
          style="width: 200px" @keyup.enter="handleQuery">
          <el-option v-for="item in groupOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="类名" prop="className">
        <el-select v-model="queryParams.className" placeholder="请选择类名" clearable filterable allow-create
          style="width: 200px" @keyup.enter="handleQuery">
          <el-option v-for="item in classNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="合约代码" prop="vtSymbol">
        <el-select v-model="queryParams.vtSymbol" placeholder="请选择合约代码" clearable filterable allow-create
          style="width: 200px" @keyup.enter="handleQuery">
          <el-option v-for="item in vtSymbolOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['kylin:futureStrategyInstance:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['kylin:futureStrategyInstance:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['kylin:futureStrategyInstance:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="DocumentAdd" @click="handleDownload"
          v-hasPermi="['kylin:trade:download']">
          下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="DocumentChecked" @click="handleLoad" v-hasPermi="['kylin:trade:load']">
          入库
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" :disabled="multiple" @click="handleQuoteDownload"
          v-hasPermi="['kylin:futureDailyQuote:download']">
          下载行情
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport"
          v-hasPermi="['kylin:futureStrategyInstance:import']">
          导入参数
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="strategyInstanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />
      <el-table-column label="服务器" align="center" prop="server" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="组名" align="center" prop="group" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="实例名" align="center" prop="instance" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="类名" align="center" prop="className" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="合约代码" align="center" prop="vtSymbol" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="showParamDialog(scope.row)"
            v-hasPermi="['kylin:futureStrategyInstance:edit']">参数
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kylin:futureStrategyInstance:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['kylin:futureStrategyInstance:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改期货策略实例对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="strategyInstanceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务器" prop="server">
          <el-input v-model="form.server" placeholder="请输入服务器" />
        </el-form-item>
        <el-form-item label="组名" prop="group">
          <el-input v-model="form.group" placeholder="请输入组名" />
        </el-form-item>
        <el-form-item label="实例名" prop="instance">
          <el-input v-model="form.instance" placeholder="请输入实例名" />
        </el-form-item>
        <el-form-item label="类名" prop="className">
          <el-input v-model="form.className" placeholder="请输入类名" />
        </el-form-item>
        <el-form-item label="合约代码" prop="vtSymbol">
          <el-input v-model="form.vtSymbol" placeholder="请输入合约代码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 策略参数查看对话框 -->
    <el-dialog v-model="paramDialogVisible" :show-close="false" width="500px" append-to-body>
      <el-table v-loading="paramLoading" :data="strategyParamList" :header-cell-style="{ background: '#fafafa' }">
        <el-table-column label="参数名" align="center" prop="paramName" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="参数值" align="center" prop="paramValue" :show-overflow-tooltip="true" />
      </el-table>
    </el-dialog>

    <!-- 下载服务器选择对话框 -->
    <el-dialog title="选择下载服务器" v-model="data.downloadDialogVisible" width="500px" append-to-body modal>
      <div class="text-center">
        <el-checkbox-group v-model="selectedServer" class="mt-4">
          <el-checkbox-button label="tencentB" class="mb-4">腾讯B服务器</el-checkbox-button>
          <el-checkbox-button label="tencentD" class="mb-4">腾讯D服务器</el-checkbox-button>
        </el-checkbox-group>
        <p class="text-xs text-gray-500 mt-2">可选择多个服务器，将按选择顺序依次下载</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDownload">取 消</el-button>
          <el-button type="primary" @click="confirmDownload">确 认 下 载</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 入库服务器选择对话框 -->
    <el-dialog title="选择入库服务器" v-model="loadDialogVisible" width="500px" append-to-body modal>
      <div class="text-center">
        <el-checkbox-group v-model="loadServer" class="mt-4">
          <el-checkbox-button label="tencentB" class="mb-4">腾讯B服务器</el-checkbox-button>
          <el-checkbox-button label="tencentD" class="mb-4">腾讯D服务器</el-checkbox-button>
        </el-checkbox-group>
        <p class="text-xs text-gray-500 mt-2">可选择多个服务器，将按选择顺序依次入库</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelLoad">取 消</el-button>
          <el-button type="primary" @click="confirmLoad">确 认 入 库</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 下载行情对话框 -->
    <el-dialog title="下载合约行情" v-model="quoteDialogVisible" width="500px" append-to-body modal>
      <div class="text-center">
        <el-checkbox-group v-model="selectedContracts" class="mt-4">
          <template v-for="contract in selectedRowsContracts" :key="contract">
            <el-checkbox-button :label="contract" class="mb-4">{{ contract }}</el-checkbox-button>
          </template>
        </el-checkbox-group>
        <p class="text-xs text-gray-500 mt-2">可选择多个合约，将按选择顺序依次下载行情数据</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelQuoteDownload">取 消</el-button>
          <el-button type="primary" @click="confirmQuoteDownload">确 认 下 载</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FutureStrategyInstance">
import {
  addFutureStrategyInstance,
  delFutureStrategyInstance,
  getFutureStrategyInstance,
  importFutureStrategyInstance,
  listFutureStrategyInstance,
  updateFutureStrategyInstance
} from '@/api/kylin/futureStrategyInstance'
import {
  listFutureStrategyParam
} from '@/api/kylin/futureStrategyParam'
import {
  downloadTrade,
  loadTrade
} from '@/api/kylin/trade.js'
import { fetchFutureQuote } from '@/api/kylin/futureQuote' // 导入下载行情API
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentInstance, reactive, ref, toRefs, computed } from 'vue'

const { proxy } = getCurrentInstance()

// 响应式数据
const strategyInstanceList = ref([])
const strategyParamList = ref([])
const open = ref(false)
const paramDialogVisible = ref(false)
const loading = ref(true)
const paramLoading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
// 下拉选择框选项数据
const serverOptions = ref([])
const groupOptions = ref([])
const instanceOptions = ref([])
const classNameOptions = ref([])
const vtSymbolOptions = ref([])
// 下载行情相关状态
const quoteDialogVisible = ref(false)
const selectedContracts = ref([])


const importForm = reactive({
  server: '',
  group: ''
})
const importFormRules = reactive({
  server: [
    { required: true, message: '请输入服务器', trigger: 'blur' }
  ],
  group: [
    { required: true, message: '请输入组名', trigger: 'blur' }
  ]
})

// 下载和入库相关状态
const selectedServer = ref([])
const downloading = ref(false)
const loadDialogVisible = ref(false)
const loadServer = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    server: undefined,
    group: undefined,
    instance: undefined,
    className: undefined,
    vtSymbol: undefined
  },
  rules: {
    server: [
      { required: true, message: '服务器不能为空', trigger: 'blur' }
    ],
    group: [
      { required: true, message: '组名不能为空', trigger: 'blur' }
    ],
    instance: [
      { required: true, message: '实例名不能为空', trigger: 'blur' }
    ],
    className: [
      { required: true, message: '类名不能为空', trigger: 'blur' }
    ],
    vtSymbol: [
      { required: true, message: '合约代码不能为空', trigger: 'blur' }
    ]
  },
  // 下载对话框相关状态
  downloadDialogVisible: false
})

const { queryParams, form, rules } = toRefs(data)

// 计算属性：获取选中行的合约代码
const selectedRowsContracts = computed(() => {
  return getSelectedRowsContracts();
})

/** 查询期货策略实例列表 */
function getList() {
  loading.value = true
  listFutureStrategyInstance(queryParams.value).then(response => {
    // 更严格的数据类型检查和处理
    try {
      // 空值保护
      if (!response || typeof response !== 'object') {
        console.error('响应数据格式错误:', response)
        strategyInstanceList.value = []
        total.value = 0
        loading.value = false
        return
      }

      // 严格检查并处理rows数据 - 根据实际返回格式，数据在response.data.rows中
      if (response.data && typeof response.data === 'object') {
        // 优先检查response.data.rows
        if (response.data.rows && typeof response.data.rows === 'object') {
          strategyInstanceList.value = Array.isArray(response.data.rows) ? response.data.rows :
            (typeof response.data.rows === 'string' ? JSON.parse(response.data.rows || '[]') : [])
        } else {
          // 如果data对象中没有rows，则检查data本身
          strategyInstanceList.value = Array.isArray(response.data) ? response.data :
            (typeof response.data === 'string' ? JSON.parse(response.data || '[]') : [])
        }

        // 从response.data中获取total
        if (response.data.total !== undefined) {
          total.value = typeof response.data.total === 'number' ? response.data.total :
            (typeof response.data.total === 'string' ? Number(response.data.total) || 0 : 0)
        } else if (typeof response.total === 'number') {
          // 备选：直接从response获取total
          total.value = response.total
        } else if (typeof response.total === 'string') {
          total.value = Number(response.total) || 0
        } else {
          // 兜底方案
          total.value = strategyInstanceList.value.length
        }
      } else if (response.rows && typeof response.rows === 'object') {
        // 备选方案：直接从response获取rows
        strategyInstanceList.value = Array.isArray(response.rows) ? response.rows :
          (typeof response.rows === 'string' ? JSON.parse(response.rows || '[]') : [])

        // 直接从response获取total
        total.value = typeof response.total === 'number' ? response.total :
          (typeof response.total === 'string' ? Number(response.total) || 0 : strategyInstanceList.value.length)
      } else {
        // 兜底方案
        strategyInstanceList.value = []
        total.value = 0
      }

      console.log('数据处理完成:', {
        rowsLength: strategyInstanceList.value.length,
        total: total.value,
        responseFormat: Object.keys(response || {})
      })

      // 更新下拉选项
      updateSelectOptions()

    } catch (e) {
      console.error('数据处理异常:', e)
      // 异常情况下强制重置为安全的空数组
      strategyInstanceList.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }).catch(error => {
    console.error('查询请求失败:', error)
    proxy.$modal.msgError('查询失败，请稍后重试')
    // 错误情况下确保数据安全
    strategyInstanceList.value = []
    total.value = 0
    loading.value = false
  })
}

/** 更新下拉选项数据 */
function updateSelectOptions() {
  try {
    const allData = strategyInstanceList.value || []

    // 确保allData是数组
    if (!Array.isArray(allData)) {
      console.warn('updateSelectOptions: allData不是数组:', allData)
      return
    }

    // 提取不重复的服务器选项
    serverOptions.value = [...new Set(allData
      .map(item => item && item.server)
      .filter(server => server && typeof server === 'string'))]

    // 提取不重复的组名选项
    groupOptions.value = [...new Set(allData
      .map(item => item && item.group)
      .filter(group => group && typeof group === 'string'))]

    // 提取不重复的实例名选项
    instanceOptions.value = [...new Set(allData
      .map(item => item && item.instance)
      .filter(instance => instance && typeof instance === 'string'))]

    // 提取不重复的类名选项
    classNameOptions.value = [...new Set(allData
      .map(item => item && item.className)
      .filter(className => className && typeof className === 'string'))]

    // 提取不重复的合约代码选项
    vtSymbolOptions.value = [...new Set(allData
      .map(item => item && item.vtSymbol)
      .filter(vtSymbol => vtSymbol && typeof vtSymbol === 'string'))]

    console.log('下拉选项更新完成')

  } catch (error) {
    console.error('更新下拉选项失败:', error)
  }
}



/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {}
  proxy.resetForm('strategyInstanceRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 下载交易数据库文件函数 */
function handleDownload() {
  // 清空之前的选择
  selectedServer.value = [];
  // 显示下载对话框
  data.downloadDialogVisible = true;
}


/** 确认下载按钮操作 */
function confirmDownload() {
  if (!selectedServer.value || selectedServer.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个服务器");
    return;
  }

  proxy.$modal.confirm(`是否确认下载${selectedServer.value.length}个服务器的交易数据？`).then(function () {
    // 显示加载提示
    proxy.$modal.loading("正在下载数据，请稍候！");

    // 顺序下载函数
    const sequentialDownload = async (servers) => {
      for (let i = 0; i < servers.length; i++) {
        const server = servers[i];
        try {
          // 显示当前正在下载的服务器信息
          const currentServerName = server === 'tencentB' ? '腾讯B服务器' : '腾讯D服务器';
          if (servers.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.loading(`正在下载 ${currentServerName} (${i + 1}/${servers.length})，请稍候！`);
          }

          // 调用后台接口，将当前服务器ID作为参数传递
          await downloadTrade({ server_id: server });

          if (servers.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess(`${currentServerName} 下载成功`);
            // 显示下一个加载提示
            if (i < servers.length - 1) {
              const nextServer = servers[i + 1];
              const nextServerName = nextServer === 'tencentB' ? '腾讯B服务器' : '腾讯D服务器';
              proxy.$modal.loading(`正在下载 ${nextServerName} (${i + 2}/${servers.length})，请稍候！`);
            }
          }
        } catch (error) {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError(`下载失败: ${error.message || '未知错误'}`);
          data.downloadDialogVisible = false;
          return;
        }
      }

      // 所有服务器下载完成
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess(`所有${servers.length}个服务器数据下载成功`);
      getList(); // 重新加载数据列表
      data.downloadDialogVisible = false;
    };

    // 开始顺序下载
    sequentialDownload(selectedServer.value);
  }).catch(() => {
    // 用户取消确认
    data.downloadDialogVisible = false;
  });
}

/** 取消下载操作 */
function cancelDownload() {
  data.downloadDialogVisible = false;
  selectedServer.value = [];
}

/** 取消入库操作 */
function cancelLoad() {
  loadDialogVisible.value = false;
  loadServer.value = [];
}

/** 获取选中行的合约代码 */
function getSelectedRowsContracts() {
  try {
    // 安全检查：确保strategyInstanceList.value是数组
    if (!Array.isArray(strategyInstanceList.value)) {
      console.warn('strategyInstanceList不是有效的数组:', strategyInstanceList.value);
      return [];
    }

    // 安全检查：确保ids.value是数组
    if (!Array.isArray(ids.value)) {
      console.warn('ids不是有效的数组:', ids.value);
      return [];
    }

    // 安全过滤选中行
    const selectedRows = strategyInstanceList.value.filter(item =>
      item && typeof item === 'object' && item.id !== undefined &&
      ids.value.includes(item.id)
    );

    // 安全提取和去重合约代码
    const contractSymbols = selectedRows
      .map(row => row && row.vtSymbol)
      .filter(symbol => symbol && typeof symbol === 'string');

    return [...new Set(contractSymbols)];
  } catch (error) {
    console.error('获取选中行合约代码出错:', error);
    return [];
  }
}

/** 下载行情操作 */
function handleQuoteDownload() {
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个记录");
    return;
  }

  // 获取选中行的唯一合约代码
  selectedContracts.value = getSelectedRowsContracts();

  if (selectedContracts.value.length === 0) {
    proxy.$modal.msgWarning("选中的记录中没有有效的合约代码");
    return;
  }

  // 显示下载行情对话框
  quoteDialogVisible.value = true;
}

/** 取消下载行情操作 */
function cancelQuoteDownload() {
  quoteDialogVisible.value = false;
  selectedContracts.value = [];
}

/** 确认下载行情操作 */
function confirmQuoteDownload() {
  if (!selectedContracts.value || selectedContracts.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个合约");
    return;
  }

  proxy.$modal.confirm(`是否确认下载${selectedContracts.value.length}个合约的行情数据？`).then(function () {
    // 显示加载提示
    proxy.$modal.loading("正在下载行情数据，请稍候！");

    // 顺序下载函数
    const sequentialQuoteDownload = async (contracts) => {
      for (let i = 0; i < contracts.length; i++) {
        const contract = contracts[i];
        try {
          // 显示当前正在下载的合约信息
          if (contracts.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.loading(`正在下载 ${contract} (${i + 1}/${contracts.length})，请稍候！`);
          }

          // 调用后台下载行情接口，传递合约代码参数
          await fetchFutureQuote(contract);

          if (contracts.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess(`${contract} 行情数据下载成功`);
            // 显示下一个加载提示
            if (i < contracts.length - 1) {
              const nextContract = contracts[i + 1];
              proxy.$modal.loading(`正在下载 ${nextContract} (${i + 2}/${contracts.length})，请稍候！`);

              // 下载完一个合约后等待3秒再下载下一个，避免被服务器限流
              proxy.$modal.msgSuccess(`等待1秒后开始下载下一个合约...`);
              await new Promise(resolve => setTimeout(resolve, 1000));
            }
          }
        } catch (error) {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError(`下载失败: ${error.message || '未知错误'}`);
          quoteDialogVisible.value = false;
          return;
        }
      }

      // 所有合约下载完成
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess(`所有${selectedContracts.value.length}个合约行情数据下载成功`);
      quoteDialogVisible.value = false;
    };

    // 开始顺序下载
    sequentialQuoteDownload(selectedContracts.value);
  }).catch(() => {
    // 用户取消确认
    quoteDialogVisible.value = false;
  });
}

/** 入库操作 */
function handleLoad() {
  // 清空之前的选择
  loadServer.value = [];
  // 显示入库对话框
  loadDialogVisible.value = true;
}

/** 确认入库操作 */
function confirmLoad() {
  if (!loadServer.value || loadServer.value.length === 0) {
    proxy.$modal.msgWarning("请选择至少一个服务器");
    return;
  }

  proxy.$modal.confirm(`是否确认将${loadServer.value.length}个服务器的下载文件导入数据库？`).then(function () {
    // 显示加载提示
    proxy.$modal.loading("正在导入数据，请稍候！");

    // 顺序入库函数
    const sequentialLoad = async (servers) => {
      for (let i = 0; i < servers.length; i++) {
        const server = servers[i];
        try {
          // 显示当前正在入库的服务器信息
          const currentServerName = server === 'tencentB' ? '腾讯B服务器' : '腾讯D服务器';
          if (servers.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.loading(`正在导入 ${currentServerName} (${i + 1}/${servers.length})，请稍候！`);
          }

          // 调用后台入库接口，传递服务器参数
          await loadTrade({ server_id: server });

          if (servers.length > 1) {
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess(`${currentServerName} 导入成功`);
            // 显示下一个加载提示
            if (i < servers.length - 1) {
              const nextServer = servers[i + 1];
              const nextServerName = nextServer === 'tencentB' ? '腾讯B服务器' : '腾讯D服务器';
              proxy.$modal.loading(`正在导入 ${nextServerName} (${i + 2}/${servers.length})，请稍候！`);
            }
          }
        } catch (error) {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError(`导入失败: ${error.message || '未知错误'}`);
          loadDialogVisible.value = false;
          return;
        }
      }

      // 所有服务器入库完成
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess(`所有${servers.length}个服务器数据导入成功`);
      getList(); // 重新加载数据列表
      loadDialogVisible.value = false;
    };

    // 开始顺序入库
    sequentialLoad(loadServer.value);
  }).catch(() => {
    // 用户取消确认
    loadDialogVisible.value = false;
  });
}

/** 导入按钮操作 */
function handleImport() {
  // 显示确认对话框
  ElMessageBox.confirm('确定要导入策略参数吗？系统将自动在特定目录下查找cta_strategy_setting.json文件。', '导入参数确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      // 显示加载状态
      const loading = ElLoading.service({ lock: true, text: '导入中...', background: 'rgba(0, 0, 0, 0.7)' })

      // 调用导入API，不需要传递server和group参数
      const response = await importFutureStrategyInstance()

      // 显示成功信息
      ElMessage.success(response.msg)

      // 刷新列表
      getList()

      // 关闭加载状态
      loading.close()
    } catch (error) {
      // 显示错误信息
      ElMessage.error(error.msg || '导入失败')
    }
  }).catch(() => {
    // 用户取消导入
    ElMessage.info('已取消导入')
  })
}


/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加期货策略实例'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const instanceId = row && row.id ? row.id : ids.value
  if (!instanceId) {
    proxy.$modal.msgError('无法获取策略实例ID，请选择有效的策略实例')
    return
  }
  getFutureStrategyInstance(instanceId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改期货策略实例'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['strategyInstanceRef'].validate(valid => {
    if (valid) {
      // 显示加载状态，防止重复提交
      proxy.$modal.loading('提交中，请稍候...')

      const promise = form.value.id
        ? updateFutureStrategyInstance(form.value)
        : addFutureStrategyInstance(form.value)

      promise.then(response => {
        proxy.$modal.closeLoading()
        proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功')
        open.value = false
        getList()
      }).catch(error => {
        proxy.$modal.closeLoading()
        console.error('提交失败:', error)
        proxy.$modal.msgError(`操作失败: ${error.message || '未知错误'}`)
      })
    }
  })
}


/** 删除按钮操作 */
function handleDelete(row) {
  const instanceIds = row && row.id ? [row.id] : ids.value
  console.log('删除操作的instanceIds:', instanceIds)
  if (!instanceIds || instanceIds.length === 0) {
    proxy.$modal.msgError('请选择要删除的策略实例')
    return
  }
  proxy.$modal.confirm('是否确认删除选中的期货策略实例？').then(() => {
    console.log('发送删除请求，instanceIds:', instanceIds)
    return delFutureStrategyInstance(instanceIds)
  }).then(response => {
    console.log('删除请求响应:', response)
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(error => {
    console.error('删除请求失败:', error)
  })
}

/** 显示策略参数对话框 */
function showParamDialog(row) {
  if (!row || !row.instance) {
    proxy.$modal.msgError('无法获取策略实例名称，请选择有效的策略实例')
    return
  }

  // 打开对话框
  paramDialogVisible.value = true

  // 查询策略参数
  queryStrategyParams(row.instance)
}

/** 根据实例名查询策略参数 */
function queryStrategyParams(instance) {
  paramLoading.value = true

  // 使用listFutureStrategyParam API，传递instance作为查询条件
  listFutureStrategyParam({ strategyInstance: instance }).then(response => {
    strategyParamList.value = response.rows || []
    paramLoading.value = false
  }).catch(error => {
    console.error('查询策略参数失败:', error)
    proxy.$modal.msgError('查询策略参数失败')
    paramLoading.value = false
  })
}

// 获取下拉选择框数据
async function loadSelectOptions() {
  try {
    // 这里我们从现有数据中提取唯一值作为选项
    // 实际项目中应该调用专门的API获取distinct值
    const response = await listFutureStrategyInstance({ pageNum: 1, pageSize: 1000 }) // 获取足够多的数据来提取选项

    // 安全地获取和处理数据
    let allData = []

    // 检查响应格式，优先从response.data.rows获取
    if (response && response.data && typeof response.data === 'object') {
      if (response.data.rows && typeof response.data.rows === 'object') {
        allData = Array.isArray(response.data.rows) ? response.data.rows : []
      } else if (Array.isArray(response.data)) {
        allData = response.data
      }
    }
    // 备选：从response.rows获取
    else if (response && response.rows && typeof response.rows === 'object') {
      allData = Array.isArray(response.rows) ? response.rows : []
    }

    console.log('loadSelectOptions: 获取到的数据行数:', allData.length)

    // 安全地提取唯一值
    serverOptions.value = [...new Set(allData
      .map(item => item && item.server)
      .filter(server => server && typeof server === 'string'))]

    groupOptions.value = [...new Set(allData
      .map(item => item && item.group)
      .filter(group => group && typeof group === 'string'))]

    instanceOptions.value = [...new Set(allData
      .map(item => item && item.instance)
      .filter(instance => instance && typeof instance === 'string'))]

    classNameOptions.value = [...new Set(allData
      .map(item => item && item.className)
      .filter(className => className && typeof className === 'string'))]

    vtSymbolOptions.value = [...new Set(allData
      .map(item => item && item.vtSymbol)
      .filter(vtSymbol => vtSymbol && typeof vtSymbol === 'string'))]

    console.log('下拉选择框数据加载完成')

  } catch (error) {
    console.error('加载下拉选项失败:', error)
    // 出错时重置为安全的空数组
    serverOptions.value = []
    groupOptions.value = []
    instanceOptions.value = []
    classNameOptions.value = []
    vtSymbolOptions.value = []
  }
}

// 初始化数据
getList()
loadSelectOptions()
</script>